import * as vueTemplateCompiler from "vue-template-compiler";
import BabelConfig_vite from "../../babel.config_vite";
import * as babel from "@babel/core";
import {TransformResult} from "vite";
import MagicString from 'magic-string';

let DEFAULT_FILTER_FILE = /\.(vue)$/

/**
 * 预编译vue2的脚本代码块
 */
export function vitePluginVue2BabelScriptBlock() {
  const babelConfig = BabelConfig_vite()
  return {
    name: 'vite:vitePluginVue2BabelScriptBlock',
    enforce: 'pre', // 也是使用预编译
    transform(code: string, id: string): Promise<TransformResult> | TransformResult {
      if (!id.includes('?') && DEFAULT_FILTER_FILE.test(id)) {
        const sfcDescriptor = vueTemplateCompiler.parseComponent(code);
        let script = sfcDescriptor.script
        if (script) {
          let filename = `${id}?lang=.${script.lang}`
          const babelResult = babel.transformSync(script.content, {
            filename,
            ...babelConfig,
            sourceMaps: true,
            sourceRoot: script.content,
            sourceType: 'module',
          })
          let magicString = new MagicString(code);
          magicString.overwrite(script.start, script.end, '\n' + babelResult.code + '\n')
          return {
            code: magicString.toString(),
            map: magicString.generateDecodedMap({
              includeContent: true,
              hires: true,
              file: id,
              source: code
            }),
          }
        }
      }
    }
  }
}

/**
 * "vite-plugin-vue2": "2.0.3",
 *     "vue-template-compiler": "2.6.12"
 *         "@babel/core": "^7.24.9",
 *     "@babel/plugin-proposal-class-properties": "^7.18.6",
 *     "@babel/plugin-proposal-decorators": "^7.24.7",
 *     "@babel/plugin-proposal-private-methods": "^7.18.6",
 *     "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
 *     "@babel/plugin-transform-private-methods": "^7.24.7",
 *     "@babel/preset-env": "^7.24.8",
 *     "@babel/preset-typescript": "^7.24.7",
 *     "@types/babel__core": "^7.20.5",
 */
